package rpc

import (
	"awesomeTask/application/timer"
	"awesomeTask/application/variable"
	"awesomeTask/commom/MessageHelper"
	event2 "awesomeTask/system/event"
	"awesomeTask/system/helper"
	log2 "awesomeTask/system/log"
	"errors"
	"net"
)

const TimeOut = "504"

/**
在集群中选择某台机器进行远程调用
*/
func RpcCall(event string, params map[string]interface{}, conn net.Conn, timeout int64) (interface{}, error) {
	defer func() {
		if r := recover(); r != nil {
			log2.GetLogger().Error("rpc error" + helper.PrintStackTrace(r.(error)))
		}
	}()
	uniqueEvent := event2.GetTmpEvent(event)
	eventChnnel := make(chan interface{})
	isClose := false
	event2.RegisterOne(uniqueEvent, func(args ...interface{}) {
		data := args[0]
		if isClose == false {
			eventChnnel <- data
		}
	})
	params["realEvent"] = event
	params["callBackEvent"] = uniqueEvent
	MessageHelper.SendEvent(variable.ON_CALLBACK_EVENT, params, conn)
	timer.SetTimeOut(func() {
		if isClose == false {
			eventChnnel <- TimeOut
		}
	}, timeout)
	data := <-eventChnnel
	close(eventChnnel)
	isClose = true
	if data != TimeOut {
		return data.(map[string]interface{})["result"], nil
	}
	return nil, errors.New("rpc failed cause TimedOut")
}
